package com.wny.backend;

import java.net.*;
import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStream;
import java.io.InputStreamReader;
import java.io.OutputStream;

public class SocketsClient {

	private int serverPort = 8888;
	private Socket mySocket;
	private static SocketsClient clientSocket;

	private SocketsClient(String serverIP) {
		try {
			mySocket = new Socket(serverIP, serverPort);
		} catch (UnknownHostException e) {
			e.printStackTrace();
		} catch (IOException e) {
			e.printStackTrace();
		}
	}

	public static SocketsClient getSocket() {
//		if (clientSocket == null) {
//			clientSocket = new SocketsClient();
//		}
		return clientSocket;
	}
	public static SocketsClient setSocket(String serverIP)
	{
		clientSocket = new SocketsClient(serverIP);
		return clientSocket;
	}


	// sends data to the server and returns server response
	public char[] sendData(byte[] toSend) throws IOException {
		char[] recieved = new char[8000];

		OutputStream out = mySocket.getOutputStream();
		InputStream in = mySocket.getInputStream();
		InputStreamReader inRead = new InputStreamReader(in);
		BufferedReader buffRead = new BufferedReader(inRead);
		out.write(toSend);
		buffRead.read(recieved);
		return recieved;
	}

	public void sendNonblocking(byte[] toSend) throws IOException {
		OutputStream out = mySocket.getOutputStream();
		out.write(toSend);
	}

	// closes connection
	public void closeConnection() throws IOException {

		mySocket.close();
	}

}
